//
//  LZTopicViewController.m
//  LZBS
//
//  Created by 郝庆 on 16/6/10.
//  Copyright © 2016年 haoqing. All rights reserved.
//
#import "LZTopicViewController.h"
#import "LZRefreshHeader.h"
#import "LZRefreshFooter.h"
#import "LZHTTPSessionManager.h"
#import "LZTopic.h"
#import "LZTopicCell.h"
#import "HQPageView.h"
#import <MJExtension.h>
#import "LZNewViewController.h"
#import <SVProgressHUD.h>
#import "LZCommentViewController.h"

@interface LZTopicViewController ()
/** 任务管理者 */
@property (nonatomic, strong) LZHTTPSessionManager *manager;
/** 所有的帖子数据 */
@property (nonatomic, strong) NSMutableArray<LZTopic *> *topics;
/** maxtime : 用来加载下一页数据 */
@property (nonatomic, copy) NSString *maxtime;
/** 仅仅为了点语法能够点出来*/
- (NSString *)aParam;
@end

@implementation LZTopicViewController

#pragma mark - 仅仅为了消除警告
- (LZTopicType)type
{
    return 0;
}

static NSString * const LZTopicCellId = @"topic";
#pragma mark - 懒加载
- (LZHTTPSessionManager *)manager
{
    if (!_manager) {
        _manager = [LZHTTPSessionManager manager];
    }
    return _manager;
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUpTableView];
    
    [self setUpRefresh];
    
    // 监听通知
    [self setUpNote];
}

- (void)setUpNote
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tabBarButtonDidRepeatClick) name:LZTabBarButtonDidRepeatClickNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(titleButtonDidRepeatClick) name:LZTitleButtonDidRepeatClickNotification object:nil];
}

- (void)setUpRefresh
{
    self.tableView.mj_header = [LZRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopics)];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [LZRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopics)];
}

- (void)setUpTableView
{
    self.tableView.contentInset = UIEdgeInsetsMake(64 + 40, 0, 49, 0);
    self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    self.tableView.backgroundColor = LZCommonBgColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([LZTopicCell class]) bundle:nil] forCellReuseIdentifier:LZTopicCellId];
    self.tableView.rowHeight = 200;
    
    HQPageView *pageView = [HQPageView pageView];
    pageView.frame = CGRectMake(0, 0, self.tableView.lz_width, 80);
    pageView.imageNames = @[@"img_00",@"img_01",@"img_02",@"img_03",@"img_04"];
    self.tableView.tableHeaderView = pageView;
}

#pragma mark - 判断是精华还是新帖
- (NSString *)aParam
{
    if (self.parentViewController.class == [LZNewViewController class]) {
        return @"newlist";
    }
    return @"list";
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 监听
/**
 *  监听TabBar按钮的重复点击
 */
- (void)tabBarButtonDidRepeatClick
{
    
    // 如果当前控制器的view不在window上，就直接返回,否则这个方法调用五次
    if (self.view.window == nil) return;
    
    // 如果当前控制器的view跟window没有重叠，就直接返回
    if (![self.view lz_intersectWithView:self.view.window]) return;
    
    // 进行下拉刷新
    [self.tableView.mj_header beginRefreshing];
}

/**
 *  监听标题按钮的重复点击
 */
- (void)titleButtonDidRepeatClick
{
    [self tabBarButtonDidRepeatClick];
}

#pragma mark - 数据加载
- (void)loadNewTopics
{
    
    // 取消所有请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.aParam;
    params[@"c"] = @"data";
    params[@"type"] = @(self.type);
    
    __weak typeof(self) weakSelf = self;
    
    [self.manager GET:LZCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存储maxtime(方便用来加载下一页数据)
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典数组 -> 模型数组
        weakSelf.topics = [LZTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        
        // 刷新表格
        [weakSelf.tableView reloadData];
        
        // 让[刷新控件]结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error.code == NSURLErrorCancelled) {
            // 取消了任务
        } else {
            // 是其他错误
        }
        [SVProgressHUD showErrorWithStatus:@"加载数据失败"];
        // 让[刷新控件]结束刷新
        [weakSelf.tableView.mj_header endRefreshing];
    }];
}

/**
 *  加载更多
 */
- (void)loadMoreTopics
{
    // 取消所有的请求
    [self.manager.tasks makeObjectsPerformSelector:@selector(cancel)];
    
    // 参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"a"] = self.aParam;
    params[@"c"] = @"data";
    params[@"maxtime"] = self.maxtime;
    params[@"type"] = @(self.type);
    
    __weak typeof(self) weakSelf = self;
    
    // 发送请求
    [self.manager GET:LZCommonURL parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 存储这页对应的maxtime
        weakSelf.maxtime = responseObject[@"info"][@"maxtime"];
        
        // 字典数组 -> 模型数组
        NSArray<LZTopic *> *moreTopics = [LZTopic mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        [weakSelf.topics addObjectsFromArray:moreTopics];
        
        // 刷新表格
        [weakSelf.tableView reloadData];
        
        // 让[刷新控件]结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [SVProgressHUD showErrorWithStatus:@"加载数据失败"];
        [SVProgressHUD dismiss];
        
        // 让[刷新控件]结束刷新
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
    
}

#pragma mark - 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:LZTopicCellId];
    
    cell.topic = self.topics[indexPath.row];
    return cell;
}

#pragma mark - 代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return self.topics[indexPath.row].cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    LZCommentViewController *comment = [[LZCommentViewController alloc] init];
    comment.topic = self.topics[indexPath.row];
    [self.navigationController pushViewController:comment animated:YES];
}

@end
